package com.me.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.me.model.MessageDto;
import com.me.netty.global.ChannelSupervise;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@ChannelHandler.Sharable // 设置通道共享
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame){
        Channel channel = ctx.channel();
        // 返回应答消息
        String content = frame.text();
        log.info("获取内容:id={},content={}",channel.id(),content);
        MessageDto messageDto = JSONObject.parseObject(content, MessageDto.class);
        switch (messageDto.getType()){
            case "heartbeat":
                log.info("heartbeat 心跳");
                break;
            case "bind":
                log.info("bind 操作");
                //添加连接
                String userName = StringUtils.isEmpty(messageDto.getContent())?"陌生人":messageDto.getContent();
                ChannelSupervise.addChannel(ctx.channel(), userName);
                break;
            case "message":
                log.info("message 接受");
                String shortText = channel.id().asShortText();
                String existUserName = ChannelSupervise.getUseMap().get(shortText);
                messageDto.setFrom(existUserName);
                TextWebSocketFrame tws = new TextWebSocketFrame(JSONObject.toJSONString(messageDto));
                // 群发消息给其他人
                log.info("群发消息给其他人");
                ChannelSupervise.send2AllOther(tws, channel);
                break;
            default:
                log.info("default");
                break;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        log.info("连接用户:{}",channel.id().asShortText());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        Channel channel = ctx.channel();
        //断开连接
        ChannelSupervise.removeChannel(ctx.channel());
        log.info("断连用户:{}",channel.id().asShortText());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        ctx.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        log.error("exceptionCaught",cause);
        ctx.close();
    }
}
